package mviewer.renderer.software.lighting;

import java.awt.Color;
import mviewer.renderer.software.interfaces.ILighting;
import mviewer.types.Camera;
import mviewer.types.IVector;
import mviewer.types.Material;
import mviewer.types.VectorData;
import mviewer.types.VectorUtil;

public class DiffuseLight implements ILighting {

	private IVector position;
	private float intensity;

	public DiffuseLight() {
		this(new VectorData(0f, 0f, 900f), 1f);
	}

	public DiffuseLight(IVector position, float intensity) {
		this.position = position;
		this.intensity = intensity;
	}

	@Override
	public void setCamera(Camera camera) { }

	public float getIntensity() {
		return intensity;
	}

	public void setIntensity(float intensity) {
		this.intensity = intensity;
	}

	public IVector getPosition() {
		return position;
	}

	@Override
	public Color renderColor(IVector v, IVector normal, Material material) {
		// renders surface normal scalar normalized(pointPosition - lightPos)
		IVector ambient = material.getAmbientColor(),
				diffuse = material.getDiffuseColor();
		float r, g, b,
			lightDirX = v.getX() - position.getX(),
			lightDirY = v.getY() - position.getY(),
			lightDirZ = v.getZ() - position.getZ(),
			lightDirLength = VectorUtil.length(lightDirX, lightDirY, lightDirZ);
		lightDirX /= lightDirLength;
		lightDirY /= lightDirLength;
		lightDirZ /= lightDirLength;
		float brightness = VectorUtil.scalar(normal.getX(), normal.getY(), normal.getZ(), lightDirX, lightDirY, lightDirZ);

		if (brightness < 0)
			brightness = 0;
		else if (brightness > 1)
			brightness = 1;

		brightness *= intensity;
		r = (ambient.getX() + diffuse.getX() * brightness) / 2;
		g = (ambient.getY() + diffuse.getY() * brightness) / 2;
		b = (ambient.getZ() + diffuse.getZ() * brightness) / 2;

		return new Color(r, g, b);
	}
}